package cn.edu.xjtu.data_structure.chapter02_stack_queue.queue;

import cn.edu.xjtu.data_structure.chapter01_linearlist.linkedlist.Link;

/**
 * @author yjq
 * @version 1.0
 * @date 2021/9/14 21:40
 */
public class LQueue<T> implements QueueADT<T> {
    private Link<T> front;//指向队首元素的指针
    private Link<T> rear;//指向队尾元素的指针
    private int size=0;//队列中实际的元素个数

    private void setUp() {
        front = rear = null;
    }

    public LQueue() {
        setUp();
    }

    public LQueue(int size) {
        setUp();
    }

    @Override
    public void clear() {
        front = rear = null;
    }

    @Override
    public void enqueue(T it) {//进队
        if (isEmpty()) {
            front = rear = new Link<T>(it, null);//队列为空
        } else {
            rear.setNext(new Link<T>(it, null));
            rear = rear.getNext();//尾指针后移
        }
        size++;

    }

    @Override
    public T dequeue() {//出队
        if (isEmpty()) {
            System.out.println("queue is empty");
            return null;
        }
        T it = front.getElement();
        front = front.getNext();
        if (front == null) rear = null;//如果队空了，也要将尾指针设为null
        size--;
        return it;
    }

    @Override
    public T firstValue() {
        if (isEmpty()) {
            System.out.println("queue is empty");
            return null;
        }
        return front.getElement();
    }

    @Override
    public boolean isEmpty() {
        return front == null;
    }

    @Override
    public boolean isFull() {
        return false;
    }

    @Override
    public void print() {
        if (isEmpty()) {
            System.out.println("queue is empty");
            return;
        }
        Link<T> temp = front;
        if (temp == rear) {
            System.out.println(temp.getElement());
            return;
        }
        while (temp != rear) {
            System.out.print(temp.getElement() + " ");
            temp = temp.getNext();
        }
        System.out.println(temp.getElement());
    }

    @Override
    public int size() {
        return size;
    }
}
